﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace SearchEngineScraper
{
    public partial class Form1 : Form
    {
        private CancellationTokenSource cts;
        private readonly HttpClient httpClient;

        public Form1()
        {
            InitializeComponent();
            httpClient = new HttpClient();
            ConfigureHttpClient();
            btnStop.Enabled = false;
        }

        private void ConfigureHttpClient()
        {
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            httpClient.Timeout = TimeSpan.FromSeconds(10);
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            string keyword = txtKeyword.Text.Trim();
            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("请输入搜索关键字");
                return;
            }

            txtBaiduResult.Clear();
            txtBingResult.Clear();
            btnSearch.Enabled = false;
            btnStop.Enabled = true;
            cts = new CancellationTokenSource();

            try
            {
                await Task.WhenAll(
                    GetBaiduResultAsync(keyword, cts.Token),
                    GetBingResultAsync(keyword, cts.Token)
                );
            }
            catch (OperationCanceledException)
            {
                MessageBox.Show("搜索已取消");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }
            finally
            {
                btnSearch.Enabled = true;
                btnStop.Enabled = false;
            }
        }

        private async Task GetBaiduResultAsync(string keyword, CancellationToken ct)
        {
            try
            {
                txtBaiduResult.Text = "正在从百度获取数据...";
                string url = $"https://www.baidu.com/s?wd={Uri.EscapeDataString(keyword)}";
                string html = await GetWebPageAsync(url, ct);

                this.Invoke((Action)(() =>
                {
                    txtBaiduResult.Text = html.Length > 200
                        ? html.Substring(0, 200) + "..."
                        : html;
                }));
            }
            catch (Exception ex)
            {
                this.Invoke((Action)(() =>
                {
                    txtBaiduResult.Text = $"百度获取失败: {ex.Message}";
                }));
            }
        }

        private async Task GetBingResultAsync(string keyword, CancellationToken ct)
        {
            try
            {
                txtBingResult.Text = "正在从Bing获取数据...";
                string url = $"https://www.bing.com/search?q={Uri.EscapeDataString(keyword)}";
                string html = await GetWebPageAsync(url, ct);

                this.Invoke((Action)(() =>
                {
                    txtBingResult.Text = html.Length > 200
                        ? html.Substring(0, 200) + "..."
                        : html;
                }));
            }
            catch (Exception ex)
            {
                this.Invoke((Action)(() =>
                {
                    txtBingResult.Text = $"Bing获取失败: {ex.Message}";
                }));
            }
        }

        private async Task<string> GetWebPageAsync(string url, CancellationToken ct)
        {
            HttpResponseMessage response = await httpClient.GetAsync(url, ct);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            cts?.Cancel();
            btnStop.Enabled = false;
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            httpClient?.Dispose();
        }
    }
}